package com.dangdang.controller;

import com.dangdang.entity.Address;
import com.dangdang.entity.User;
import com.dangdang.service.AddressService;
import com.dangdang.service.impl.AddressServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/address")
public class AddressController {
    private AddressService as = new AddressServiceImpl();

    @RequestMapping("/selectAllAddr")
    public String selectAllAddr( Model model,HttpSession session){
        User user = (User)session.getAttribute("user");
        List<Address> addresses = as.selectAllAddr(user.getId());
        model.addAttribute("addresses",addresses);
        return "forward:/address/my_address.jsp";
    }
    @RequestMapping("/selectAllAddres")
    public String selectAllAddres( Model model,HttpSession session){
        User user = (User)session.getAttribute("user");
        List<Address> addresses = as.selectAllAddr(user.getId());
        model.addAttribute("addresses",addresses);
        return "forward:/order/address_form.jsp";
    }

    @RequestMapping("/delete")
    public String delete(int id){
        Address address = as.selectById(id);
        //1删0留
        address.setDelete_state(1);
        as.update(address);
        return "redirect:/address/selectAllAddr.do";
    }
    @RequestMapping("/updateState")
    public String updateState(int id, HttpSession session){
        User user = (User)session.getAttribute("user");
        List<Address> addresses = as.selectAllAddr(user.getId());
        for(Address addr:addresses){
            if(addr.getId()==id){
                addr.setSelected_state(1);
            }else{
                addr.setSelected_state(0);
            }
            as.update(addr);
        }
        return "redirect:/address/selectAllAddr.do";
    }
    @RequestMapping("/insert")
    public String insert(Address address,HttpSession session){
        User user = (User)session.getAttribute("user");
        address.setUid(user.getId());
        address.setSelected_state(0);
        address.setDelete_state(0);
        as.insert(address);
        return "redirect:/address/selectAllAddr.do";
    }
}
